package com.corpgovernment.organization.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;

import com.corpgovernment.api.organization.bo.OrgAndDataPermissionInfoBO;
import com.corpgovernment.api.organization.model.org.GetOrgTreeResponse;
import com.corpgovernment.api.organization.model.org.queryorgparentcompany.OrgAndParentCompanyInfoDTO;
import com.corpgovernment.api.organization.model.org.queryorgparentcompany.OrgInfoDTO;
import com.corpgovernment.common.base.ResourceInfo;
import com.corpgovernment.common.common.CorpBusinessException;
import com.corpgovernment.organization.constant.OrganizationConst;
import com.corpgovernment.organization.constant.OrganizationResponseCodeEnum;
import com.corpgovernment.organization.entity.db.MbOrgInfo;
import com.corpgovernment.organization.enumm.OrgTypeEnum;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wangyujue
 */
@Slf4j
public class OrganizationUtil {
    public static String findRecentCompanyId(String orgId, Map<String, MbOrgInfo> orgIdMap) {
        // 查询
        MbOrgInfo mbOrgInfo = orgIdMap.get(orgId);
        if (mbOrgInfo == null) {
            return null;
        }
        if (mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT)) {
            return findRecentCompanyId(mbOrgInfo.getParentId(), orgIdMap);
        } else {
            return mbOrgInfo.getOrgId();
        }
    }

    public static MbOrgInfo findRecentCompanyInfo(String orgId, Map<String, MbOrgInfo> orgIdMap) {
        // 查询
        MbOrgInfo mbOrgInfo = orgIdMap.get(orgId);
        if (mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT)) {
            return findRecentCompanyInfo(mbOrgInfo.getParentId(), orgIdMap);
        } else {
            return mbOrgInfo;
        }
    }

    public static List<MbOrgInfo> findOrgTreeFromCurrentOrg(String currentOrgId, Map<String, MbOrgInfo> orgIdMap) {
        MbOrgInfo currentOrg = orgIdMap.get(currentOrgId);
        List<MbOrgInfo> orgList = new ArrayList<>();
        while (currentOrg != null) {
            orgList.add(0, currentOrg);
            currentOrg = orgIdMap.get(currentOrg.getParentId());
        }
        return orgList;
    }

    /**
     * 查询所有组织树，如果
     *
     * @param mbOrgInfoList
     * @param
     * @return
     */
    public static List<OrgAndDataPermissionInfoBO> buildOrgTree(List<MbOrgInfo> mbOrgInfoList, ResourceInfo
            resourceInfo, Boolean bgUser) {
        List<ResourceInfo.DeptInfo> dataPermission = Optional.ofNullable(resourceInfo).map(ResourceInfo::getDeptInfos)
                .orElse(new ArrayList<>());
        // 返回list
        List<OrgAndDataPermissionInfoBO> returnList = new ArrayList<>();

        // parentId为key的map
        Map<String, List<MbOrgInfo>> parentIdMap = mbOrgInfoList.stream()
                .filter(p -> p.getParentId() != null)
                .collect(Collectors.groupingBy(MbOrgInfo::getParentId));

        // 顶级集团数据
        List<MbOrgInfo> topLevelList = mbOrgInfoList.stream().filter(m -> m.getLevel() == 1).collect(Collectors.toList());
        // 遍历顶级集团元素，将集团加元素递归封装好数据
        for (MbOrgInfo mbOrgInfo : topLevelList) {
            if (mbOrgInfo != null) {
                OrgAndDataPermissionInfoBO getOrgTreeResponse = buildPageckgeData(mbOrgInfo, parentIdMap, dataPermission, bgUser);
                returnList.add(getOrgTreeResponse);
            }
        }

        return returnList;
    }

    /**
     * 封装树返回值
     *
     * @param mbOrgInfo
     * @param parentIdMap
     */
    private static OrgAndDataPermissionInfoBO buildPageckgeData(MbOrgInfo mbOrgInfo, Map<String, List<MbOrgInfo>> parentIdMap,
                                                                List<ResourceInfo.DeptInfo> dataPermission, Boolean bgUser) {
        Set<String> dataPermissionSet = Optional.ofNullable(dataPermission).orElse(new ArrayList<>())
                .stream().map(ResourceInfo.DeptInfo::getOrgId).collect(Collectors.toSet());

        OrgAndDataPermissionInfoBO dataPermissionInfoBO = OrgAndDataPermissionInfoBO.builder()
                .orgType(mbOrgInfo.getOrgType())
                .orgId(mbOrgInfo.getOrgId())
                .parentOrgId(mbOrgInfo.getParentId())
                .hasDataPermission(Boolean.TRUE.equals(bgUser) ? bgUser : dataPermissionSet.contains(mbOrgInfo.getOrgId()))
                .build();
        // 递归查找子级组织
        buildFindChildren(dataPermissionInfoBO, parentIdMap, dataPermissionSet, bgUser);
        return dataPermissionInfoBO;
    }

    private static OrgAndDataPermissionInfoBO buildFindChildren(OrgAndDataPermissionInfoBO dataPermissionInfoBO,
                                                   Map<String, List<MbOrgInfo>> parentIdMap, Set<String> dataPermissionSet,
                                                                Boolean bgUser) {
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(dataPermissionInfoBO.getOrgId());
        if (CollectionUtils.isNotEmpty(mbOrgInfos)) {
            if (CollectionUtils.isEmpty(dataPermissionInfoBO.getSubOrgInfoList())) {
                List<OrgAndDataPermissionInfoBO> children = new ArrayList<>(mbOrgInfos.size());
                dataPermissionInfoBO.setSubOrgInfoList(children);
            }
            List<OrgAndDataPermissionInfoBO> children = dataPermissionInfoBO.getSubOrgInfoList();
            // 排序，公司在前，部门在后
            List<MbOrgInfo> companyList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.COMPANY))
                    .collect(Collectors.toList());
            List<MbOrgInfo> departmentList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT))
                    .collect(Collectors.toList());
            List<MbOrgInfo> sortedList = new ArrayList<>(companyList.size() + departmentList.size());
            sortedList.addAll(companyList);
            sortedList.addAll(departmentList);
            for (MbOrgInfo mbOrgInfo : sortedList) {
                // 组装返回数据
                OrgAndDataPermissionInfoBO dataPermissionInfoBO1 = OrgAndDataPermissionInfoBO.builder()
                        .orgType(mbOrgInfo.getOrgType())
                        .orgId(mbOrgInfo.getOrgId())
                        .parentOrgId(mbOrgInfo.getParentId())
                        .hasDataPermission(Boolean.TRUE.equals(bgUser) ? bgUser : dataPermissionSet.contains(mbOrgInfo.getOrgId()))
                        .build();
                // 如果当前层级为部门，也就是orgType为D的话，再将D对应orgId查询员工表，将员工表中间org_id等于当前部门id的人查询出来，插入进去
                children.add(buildFindChildren(dataPermissionInfoBO1, parentIdMap, dataPermissionSet, bgUser));
            }
            dataPermissionInfoBO.setSubOrgInfoList(children);
        }
        return dataPermissionInfoBO;
    }

    /**
     * 查询所有组织树，如果
     *
     * @param mbOrgInfoList
     * @param orgId
     * @return
     */
    public static List<GetOrgTreeResponse> listOrgTree(List<MbOrgInfo> mbOrgInfoList, String orgId, Boolean ifShowChildCompany) {
        //mbOrgInfoList = mbOrgInfoList.stream().filter(e -> e.getId() >0).collect(Collectors.toList());
        // orgId为key的map
        Map<String, MbOrgInfo> orgIdMap = mbOrgInfoList.stream()
                .collect(Collectors.toMap(MbOrgInfo::getOrgId, mbOrgInfo -> mbOrgInfo));
        // parentId为key的map
        Map<String, List<MbOrgInfo>> parentIdMap = mbOrgInfoList.stream()
                .filter(p -> p.getParentId() != null)
                .collect(Collectors.groupingBy(MbOrgInfo::getParentId));
        // 返回list
        List<GetOrgTreeResponse> returnList = new ArrayList<>();

        // 指定org查询树
        if (StrUtil.isNotEmpty(orgId)) {
            MbOrgInfo mbOrgInfo = orgIdMap.get(orgId);
            if (mbOrgInfo != null) {
                GetOrgTreeResponse getOrgTreeResponse = null;
                if (ifShowChildCompany == null || !ifShowChildCompany) {
                    getOrgTreeResponse = pageckgeDataWithoutCompany(mbOrgInfo, parentIdMap);
                } else {
                    getOrgTreeResponse = pageckgeData(mbOrgInfo, parentIdMap);
                }
                returnList.add(getOrgTreeResponse);
            }
            return returnList;
        }

        // 顶级集团数据
        List<MbOrgInfo> topLevelList = mbOrgInfoList.stream().filter(m -> m.getLevel() == 1).collect(Collectors.toList());
        // 遍历顶级集团元素，将集团加元素递归封装好数据
        for (MbOrgInfo mbOrgInfo : topLevelList) {
            if (mbOrgInfo != null) {
                GetOrgTreeResponse getOrgTreeResponse = pageckgeData(mbOrgInfo, parentIdMap);
                returnList.add(getOrgTreeResponse);
            }

        }
        return returnList;
    }

    /**
     * 查询组织和所属公司信息
     *
     * @param orgInfoList 组织信息列表
     * @param orgId 组织id
     * @return 组织信息和公司信息
     */
    public static OrgAndParentCompanyInfoDTO findOrgAndCompanyInfo(List<MbOrgInfo> orgInfoList, String orgId) {
        Map<String, MbOrgInfo> orgIdMap = orgInfoList.stream()
            .collect(Collectors.toMap(MbOrgInfo::getOrgId, x -> x, (x1, x2) -> x1));
        // 当前组织
        MbOrgInfo orgInfo = orgIdMap.get(orgId);

        OrgAndParentCompanyInfoDTO orgAndParentCompanyInfo = new OrgAndParentCompanyInfoDTO();
        orgAndParentCompanyInfo.setCurrentOrgInfo(convertOrgInfoDTO(orgInfo));
        // 当前组织所属公司
        orgAndParentCompanyInfo.setParentCompanyInfo(convertOrgInfoDTO(findParentCompanyInfo(orgIdMap, orgInfo)));
        // 当前组织所属顶级组织
        orgAndParentCompanyInfo.setRootOrgInfo(convertOrgInfoDTO(findRootOrgInfo(orgIdMap, orgInfo)));
        return orgAndParentCompanyInfo;
    }

    /**
     * 查询组织关联的父级组织信息
     *
     * @param orgInfoList 组织信息列表
     * @param orgIdList 组织id列表
     * @return 组织信息和公司信息
     */
    public static List<OrgInfoDTO> findAllRelatedParentOrgList(List<MbOrgInfo> orgInfoList,
        List<String> orgIdList) {
        Map<String, MbOrgInfo> orgInfoMap = new HashMap<>();
        // 将所有组织信息以orgId为键存入Map，便于快速查找
        for (MbOrgInfo orgInfo : orgInfoList) {
            orgInfoMap.put(orgInfo.getOrgId(), orgInfo);
        }

        List<MbOrgInfo> relatedParentOrgList = new ArrayList<>();
        Set<String> relatedParentOrgIdList = new HashSet<>();
        // 遍历所有需要查找的组织ID
        for (String orgId : orgIdList) {
            String currentOrgId = orgId;
            // 沿着父级链向上查找
            while (StringUtils.isNotBlank(currentOrgId) && orgInfoMap.containsKey(currentOrgId)) {
                MbOrgInfo currentOrgInfo = orgInfoMap.get(currentOrgId);

                // 未被添加到结果列表中,则添加到结果列表
                if (!relatedParentOrgIdList.contains(currentOrgId)){
                    relatedParentOrgIdList.add(currentOrgId);
                    relatedParentOrgList.add(currentOrgInfo);
                }

                // 移动到父级组织ID，继续查找
                currentOrgId = currentOrgInfo.getParentId();
            }
        }

        return relatedParentOrgList.stream().map(OrganizationUtil::convertOrgInfoDTO).collect(Collectors.toList());
    }

    /**
     * 查询当前组织的所有父组织信息
     *
     * @param orgIdMap orgId->组织信息
     * @param orgInfo 当前组织信息
     */
    private static List<OrgInfoDTO> findAllParentOrgList(Map<String, MbOrgInfo> orgIdMap, MbOrgInfo orgInfo) {
        return null;
    }

    /**
     * 查询当前组织的父级公司信息
     *
     * @param orgIdMap orgId->组织信息
     * @param orgInfo 当前组织信息
     */
    private static MbOrgInfo findParentCompanyInfo(Map<String, MbOrgInfo> orgIdMap, MbOrgInfo orgInfo) {
        MbOrgInfo parentCompanyInfo = orgInfo;
        while (OrgTypeEnum.D.getCode().equals(parentCompanyInfo.getOrgType())) {
            parentCompanyInfo = orgIdMap.get(parentCompanyInfo.getParentId());
        }
        return parentCompanyInfo;
    }

    /**
     * 查询当前组织的顶级组织信息
     *
     * @param orgIdMap orgId->组织信息
     * @param orgInfo 当前组织信息
     */
    private static MbOrgInfo findRootOrgInfo(Map<String, MbOrgInfo> orgIdMap, MbOrgInfo orgInfo) {
        MbOrgInfo rootOrgInfo = orgInfo;
        while (StringUtils.isNotBlank(rootOrgInfo.getParentId())) {
            rootOrgInfo = orgIdMap.get(rootOrgInfo.getParentId());
        }
        return rootOrgInfo;
    }

    private static OrgInfoDTO convertOrgInfoDTO(MbOrgInfo orgInfo) {
        OrgInfoDTO orgInfoDTO = new OrgInfoDTO();
        orgInfoDTO.setOrgId(orgInfo.getOrgId());
        orgInfoDTO.setOrgType(orgInfo.getOrgType());
        orgInfoDTO.setName(orgInfo.getName());
        orgInfoDTO.setParentId(orgInfo.getParentId());
        return orgInfoDTO;
    }

    /**
     * 查询父组织id并且返回值包含当前组织id
     *
     * @param mbOrgInfoList 组织信息列表
     * @param orgId         当前的组织id
     */
    public static List<String> getParentOrgIdsAndCurrent(List<MbOrgInfo> mbOrgInfoList, String orgId) {
        Map<String, MbOrgInfo> orgInfoMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, v -> v));
        List<String> orgIds = new ArrayList<>();
        MbOrgInfo orgInfo = orgInfoMap.get(orgId);
        while (true) {
            if (orgInfo == null) {
                StringJoiner sj = new StringJoiner(System.lineSeparator());
                sj.add("组织信息列表：" + JsonUtil.toJson(mbOrgInfoList));
                sj.add("orgId：" + orgId);
                log.error(sj.toString());
                throw new CorpBusinessException(OrganizationResponseCodeEnum.GET_ORG_INFO_NULL);
            }
            orgIds.add(orgInfo.getOrgId());
            // 找到根orgId
            if (orgInfo.getLevel() == 1) {
                return orgIds;
            }
            // 不是根组织则获取父级组织信息
            orgInfo = orgInfoMap.get(orgInfo.getParentId());
        }
    }

    /**
     * 获取目标orgId的根orgId
     *
     * @param mbOrgInfoList 所有的组织信息
     * @param orgId         目标orgId
     */
    public static String getRootOrgId(List<MbOrgInfo> mbOrgInfoList, String orgId) {
        Map<String, MbOrgInfo> orgInfoMap = mbOrgInfoList.stream().collect(Collectors.toMap(MbOrgInfo::getOrgId, v -> v));
        MbOrgInfo orgInfo = orgInfoMap.get(orgId);
        while (true) {
            if (orgInfo == null) {
                StringJoiner sj = new StringJoiner(System.lineSeparator());
                sj.add("未找到此组织的根组织id,可能是传入orgId有误");
                sj.add("mbOrgInfoList:" + JsonUtil.toJson(mbOrgInfoList));
                sj.add("orgId:" + orgId);
                throw new IllegalArgumentException(sj.toString());
            }
            // 找到根orgId
            if (orgInfo.getLevel() == 1) {
                return orgInfo.getOrgId();
            }
            // 不是根组织则获取父级组织信息
            orgInfo = orgInfoMap.get(orgInfo.getParentId());
        }
    }


    private static GetOrgTreeResponse pageckgeDataWithoutCompany(MbOrgInfo mbOrgInfo, Map<String, List<MbOrgInfo>> parentIdMap) {
        GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                .id(mbOrgInfo.getOrgId())
                .label(mbOrgInfo.getName())
                .pid(mbOrgInfo.getParentId())
                .level(mbOrgInfo.getLevel())
                .type(mbOrgInfo.getOrgType())
                .orgId(mbOrgInfo.getOrgId())
                .type(mbOrgInfo.getOrgType())
                .valid(mbOrgInfo.getValid())
                .oId(mbOrgInfo.getId())
                .businessCode(mbOrgInfo.getBusinessCode())
                .parentBusinessCode(mbOrgInfo.getParentBusinessCode())
                .build();
        // 递归查找子级组织
        findChildrenWithoutCompany(getOrgTreeResponse, parentIdMap);
        return getOrgTreeResponse;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNode    当前递归节点
     * @param parentIdMap 父级id组成的map
     * @return GetOrgTreeResponse
     */
    private static GetOrgTreeResponse findChildrenWithoutCompany(GetOrgTreeResponse treeNode,
                                                                 Map<String, List<MbOrgInfo>> parentIdMap) {
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(treeNode.getOrgId());
        if (CollectionUtils.isNotEmpty(mbOrgInfos)) {
            if (CollectionUtils.isEmpty(treeNode.getChildren())) {
                List<GetOrgTreeResponse> children = new ArrayList<>(mbOrgInfos.size());
                treeNode.setChildren(children);
            }
            List<GetOrgTreeResponse> children = treeNode.getChildren();
            // 排序，公司在前，部门在后
            List<MbOrgInfo> departmentList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()))
                    .filter(mbOrgInfo -> mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT))
                    .collect(Collectors.toList());
            List<MbOrgInfo> sortedList = new ArrayList<>(departmentList.size());
            sortedList.addAll(departmentList);
            for (MbOrgInfo mbOrgInfo : sortedList) {
                // 组装返回数据
                GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                        .id(mbOrgInfo.getOrgId())
                        .label(mbOrgInfo.getName())
                        .pid(mbOrgInfo.getParentId())
                        .level(mbOrgInfo.getLevel())
                        .type(mbOrgInfo.getOrgType())
                        .orgId(mbOrgInfo.getOrgId())
                        .valid(mbOrgInfo.getValid())
                        .oId(mbOrgInfo.getId())
                        .businessCode(mbOrgInfo.getBusinessCode())
                        .build();
                // 如果当前层级为部门，也就是orgType为D的话，再将D对应orgId查询员工表，将员工表中间org_id等于当前部门id的人查询出来，插入进去
                children.add(findChildrenWithoutCompany(getOrgTreeResponse, parentIdMap));
            }
            treeNode.setChildren(children);
        }
        return treeNode;
    }

    /**
     * 封装树返回值
     *
     * @param mbOrgInfo
     * @param parentIdMap
     */
    private static GetOrgTreeResponse pageckgeData(MbOrgInfo mbOrgInfo, Map<String, List<MbOrgInfo>> parentIdMap) {
        GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                .id(mbOrgInfo.getOrgId())
                .label(mbOrgInfo.getName())
                .pid(mbOrgInfo.getParentId())
                .level(mbOrgInfo.getLevel())
                .type(mbOrgInfo.getOrgType())
                .orgId(mbOrgInfo.getOrgId())
                .type(mbOrgInfo.getOrgType())
                .valid(mbOrgInfo.getValid())
                .oId(mbOrgInfo.getId())
                .businessCode(mbOrgInfo.getBusinessCode())
                .parentBusinessCode(mbOrgInfo.getParentBusinessCode())
                .build();
        // 递归查找子级组织
        findChildren(getOrgTreeResponse, parentIdMap);
        return getOrgTreeResponse;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNode    当前递归节点
     * @param parentIdMap 父级id组成的map
     * @return GetOrgTreeResponse
     */
    private static GetOrgTreeResponse findChildren(GetOrgTreeResponse treeNode,
                                                   Map<String, List<MbOrgInfo>> parentIdMap) {
        List<MbOrgInfo> mbOrgInfos = parentIdMap.get(treeNode.getOrgId());
        if (CollectionUtils.isNotEmpty(mbOrgInfos)) {
            if (CollectionUtils.isEmpty(treeNode.getChildren())) {
                List<GetOrgTreeResponse> children = new ArrayList<>(mbOrgInfos.size());
                treeNode.setChildren(children);
            }
            List<GetOrgTreeResponse> children = treeNode.getChildren();
            // 排序，公司在前，部门在后
            List<MbOrgInfo> companyList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.COMPANY))
                    .collect(Collectors.toList());
            List<MbOrgInfo> departmentList = mbOrgInfos.stream()
                    .filter(mbOrgInfo -> StringUtils.isNotBlank(mbOrgInfo.getOrgType()) && mbOrgInfo.getOrgType().equals(OrganizationConst.DEPARTMENT))
                    .collect(Collectors.toList());
            List<MbOrgInfo> sortedList = new ArrayList<>(companyList.size() + departmentList.size());
            sortedList.addAll(companyList);
            sortedList.addAll(departmentList);
            for (MbOrgInfo mbOrgInfo : sortedList) {
                // 组装返回数据
                GetOrgTreeResponse getOrgTreeResponse = GetOrgTreeResponse.builder()
                        .id(mbOrgInfo.getOrgId())
                        .label(mbOrgInfo.getName())
                        .pid(mbOrgInfo.getParentId())
                        .level(mbOrgInfo.getLevel())
                        .type(mbOrgInfo.getOrgType())
                        .orgId(mbOrgInfo.getOrgId())
                        .valid(mbOrgInfo.getValid())
                        .oId(mbOrgInfo.getId())
                        .businessCode(mbOrgInfo.getBusinessCode())
                        .parentBusinessCode(mbOrgInfo.getParentBusinessCode())
                        .build();
                // 如果当前层级为部门，也就是orgType为D的话，再将D对应orgId查询员工表，将员工表中间org_id等于当前部门id的人查询出来，插入进去
                children.add(findChildren(getOrgTreeResponse, parentIdMap));
            }
            treeNode.setChildren(children);
        }
        return treeNode;
    }

    /**
     * 获取组织下所有部门的ID，穿透部门，不穿透公司
     */
    public static List<String> loadSubDept(String orgId, Map<String, MbOrgInfo> orgIdMap) {
        Map<String, List<MbOrgInfo>> parentIdOrgMap = new HashMap<>();
        for (Map.Entry<String, MbOrgInfo> entry : orgIdMap.entrySet()) {
            if (parentIdOrgMap.containsKey(entry.getValue().getParentId())) {
                parentIdOrgMap.get(entry.getValue().getParentId()).add(entry.getValue());
            } else {
                List<MbOrgInfo> moiList = new ArrayList<>();
                moiList.add(entry.getValue());
                parentIdOrgMap.put(entry.getValue().getParentId(), moiList);
            }
        }
        List<String> orgIdList = new ArrayList<>();
        List<MbOrgInfo> moiList = new ArrayList<>();
        while (true) {
            String id = orgIdList.remove(0);
            // load 子部门
            if (parentIdOrgMap.containsKey(id)) {
                List<MbOrgInfo> subOrgList = parentIdOrgMap.get(id).stream()
                        .filter(o -> o.getOrgType().equals(OrgTypeEnum.D.getCode()))
                        .collect(Collectors.toList());
                orgIdList.addAll(subOrgList.stream().map(MbOrgInfo::getOrgId).collect(Collectors.toList()));
            }
            if (moiList.isEmpty()) {
                break;
            }
        }
        return orgIdList;
    }
}
